//
//  HEOrderDetailsViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/29.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOrderDetailsViewController.h"
#import "HEMyOrderAddrssCell.h"
#import "GroupShadowTableView.h"
#import "GDFiterCellModel.h"
#import "GDFormModel.h"
#import "HEMyOrderGoodsCell.h"
#import "HEMyOrderDetailsFooterCell.h"
#import "HEMyOrderDoctorInfoCell.h"
#import "HEMyOrderServicePersonCell.h"
#import "HEMyOrderInfoCell.h"
#import "HEMyOrderDetailsHeadCell.h"
#import "HEMyOrderAddSubOrderCell.h"
#import "HEOrderGoodsOperationCell.h"
#import "HEMyOrderTabbarView.h"
#import "HEPayPopView.h"
#import "HEWxPayReqModel.h"
#import "HEPayResultResViewController.h"
#import "HEOrderCommentViewController.h"
#import "HEServerCommentListViewController.h"
#import "HELogisticsViewController.h"
#import "HEAfterSaleViewController.h"
#import "HEReturnLogisticsViewController.h"
#import "HEIMChatViewController.h"
#import "HEIMTWChatViewController.h"
#import "HEIMTeamViewController.h"
#import "HEQRPayView.h"
#import "HEMyOrderPayPersonCell.h"
#import "HEMyOrderAskPayCell.h"
#import "HETranspFeesModel.h"
#import "HEDocOrderTransFeesCell.h"

@interface HEOrderDetailsViewController ()<GroupShadowTableViewDelegate, GroupShadowTableViewDataSource, HEMyOrderTabbarViewDelegate, HEPayPopViewDelegate, HEMyOrderServicePersonCellDelegate, HEOrderGoodsOperationCellDelegate, HEMyOrderDoctorInfoCellDelegate>

@property (nonatomic, strong) GroupShadowTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;

@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *goodsDataSource;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, strong) HEOrderModel * order;
@property (nonatomic, strong) UILabel *statLb;
@property (nonatomic, strong) HEOrderModel *detials;

@property (nonatomic, strong) HEMyOrderTabbarView *tabbar;
@property (nonatomic, strong) NSArray <HEPaymentModel *>*paymentsList; // 支付方式
@property (nonatomic, strong) UIImageView *sealAllView;


@end

@implementation HEOrderDetailsViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPayFailure object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"订单详请";
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleDefault;

    [self initUI];
    [self initHeadView];
    
    [self loadData];
    [self loadPaydata];

    
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:KNotificationPaySuccess object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFialure) name:KNotificationPayFailure object:nil];
}

- (void)initUI {
    
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;

    self.tableView = [[GroupShadowTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight) style:UITableViewStylePlain];
    self.tableView.groupShadowDelegate = self;
    _tableView.groupShadowDataSource = self;
    _tableView.showSeparator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = CViewBgColor;
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 40)];
    v.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = v;
    [self.view addSubview:_tableView];
    
//    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).offset(ZXNavBarHeight);
//        make.right.left.equalTo(self.view);
//        make.bottom.equalTo(self.view).offset(-tabbarHeight);
//    }];
    
    
    HEMyOrderTabbarView *tabbar = [[HEMyOrderTabbarView alloc] init];
    _tabbar = tabbar;
    _tabbar.delegate = self;
    [self.view addSubview:tabbar];
    
    [tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

- (void)initHeadView {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 30)];
    UILabel *statLb = [UILabel new];
    _statLb = statLb;
    statLb.font = DYBlodFont(17);
    statLb.text = @"--";
    statLb.textColor = CPriceColor;
    [headView addSubview:statLb];
    
    [statLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView).mas_offset(10);
        make.left.equalTo(headView).mas_offset(15);
        make.right.equalTo(headView).mas_offset(-10);
        make.bottom.equalTo(headView);
    }];
    
    _tableView.tableHeaderView = headView;
}

- (void)loadData {
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KOrderDetail parameters:@{@"id":[NSNumber numberWithInteger:_orderId]} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.detials = [HEOrderModel mj_objectWithKeyValues:response.data];
        
        self.formModel.od_details = self.detials;
        self.formModel.od_transFee = self.detials.KtransFeesInfo;
        self.statLb.text = self.detials.KstatusName;
        self.tabbar.model = self.detials;
        
        [self setupTabbar];
        [self initCell2];
        [self showPayedView];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)showPayedView {
    
    if ([DYTools isBlankString:self.detials.payCode]) {
        self.sealAllView.hidden = YES;
        return;
    }
    
    if (
        self.detials.status == HEOrderStatusWaitDeliver ||
        self.detials.status == HEOrderStatusDelivered ||
        self.detials.status == HEOrderStatusFinish ||
        self.detials.status == HEOrderStatusWaitComment ||
        self.detials.status == HEOrderStatusWaitUse) {
        self.sealAllView.hidden = NO;
        [self.tableView bringSubviewToFront:self.sealAllView];
    }
}

- (void)initCell2 {
    // 总段
    _sections = [NSMutableArray array];

    NSMutableArray *classArr = [NSMutableArray array];
    
    // 判断是不是代付订单
    BOOL isProxyPerson = [self isProxyPerson];
    

    // 显示地址
    GDFiterCellModel *addAddrsModel = [GDFiterCellModel new];
    addAddrsModel.cellKlass = HEMyOrderAddrssCell.class;
    addAddrsModel.cellType = GDFiterCellTypeOrderDetailsAddres;
    addAddrsModel.cellDisplayType =  [DYTools isBlankString: self.detials.receiverProvince] ? GDCellDisplayNone : GDCellDisplayShow;

    // 商品
    GDFiterCellModel *goodsModel = [GDFiterCellModel new];
    goodsModel.cellKlass = HEMyOrderGoodsCell.class;
    goodsModel.cellType = GDFiterCellTypeOrderDetailsGoods;
    
    // 商品操作
    GDFiterCellModel *goodsOperationModel = [GDFiterCellModel new];
    goodsOperationModel.cellKlass = HEOrderGoodsOperationCell.class;
    goodsOperationModel.cellType = GDFiterCellTypeOrderDetailsGoodsOperation;
    
    // 商品段尾
    GDFiterCellModel *footerModel = [GDFiterCellModel new];
    footerModel.cellKlass = HEMyOrderDetailsFooterCell.class;
    footerModel.cellType = GDFiterCellTypeOrderDetailsGoodsFooter;
    
    // 交通费用详请
    GDFiterCellModel *transFeeModel = [GDFiterCellModel new];
    transFeeModel.cellKlass = HEDocOrderTransFeesCell.class;
    transFeeModel.cellType = GDFiterCellTypeGoodTransFeesInfo;
    transFeeModel.cellDisplayType = self.detials.visit ? GDCellDisplayShow:GDCellDisplayNone;
    
    // 医生信息
    GDFiterCellModel *doctorModel = [GDFiterCellModel new];
    doctorModel.cellKlass = HEMyOrderDoctorInfoCell.class;
    doctorModel.cellType = GDFiterCellTypeOrderDetailsDoctorInfo;
    if (_detials.channel == HEChannelTypeOfflineActive ||
        _detials.channel == HEChannelTypeSickedBed) {
        doctorModel.cellDisplayType = GDCellDisplayNone;
    }else if ( [DYTools isBlankString:self.detials.extras] ) {
        doctorModel.cellDisplayType = GDCellDisplayNone;
    }else {
        doctorModel.cellDisplayType = GDCellDisplayShow;
    }


    // 代付人信息
    GDFiterCellModel *proxyPaynModel = [GDFiterCellModel new];
    proxyPaynModel.cellKlass = HEMyOrderPayPersonCell.class;
    proxyPaynModel.cellDisplayType = !isProxyPerson && self.detials.isAgent ? GDCellDisplayShow : GDCellDisplayNone;

    // 请求代付人信息
    GDFiterCellModel *askProxyPaynModel = [GDFiterCellModel new];
    askProxyPaynModel.cellKlass = HEMyOrderAskPayCell.class;
    askProxyPaynModel.cellDisplayType = isProxyPerson && self.detials.isAgent ? GDCellDisplayShow : GDCellDisplayNone;


    // 上门服务人员
    GDFiterCellModel *serverPersonModel = [GDFiterCellModel new];
    serverPersonModel.cellKlass = HEMyOrderServicePersonCell.class;
    serverPersonModel.cellType = GDFiterCellTypeOrderDetailsServicePersonInfo;
    serverPersonModel.cellDisplayType = self.detials.serveUser == nil ? GDCellDisplayNone : GDCellDisplayShow;

    // 头
    GDFiterCellModel *headModel = [GDFiterCellModel new];
    headModel.cellKlass = HEMyOrderDetailsHeadCell.class;
    headModel.cellType = GDFiterCellTypeOrderDetailsHead;
    headModel.leftTitle = @"订单信息";
    
    // 补单信息
    GDFiterCellModel *addOrderModel = [GDFiterCellModel new];
    addOrderModel.cellKlass = HEMyOrderAddSubOrderCell.class;
    addOrderModel.cellType = GDFiterCellTypeOrderDetailsAddOrder;
    addOrderModel.cellDisplayType =  self.detials.childInfo.count == 0 ? GDCellDisplayNone : GDCellDisplayShow;

    // 订单信息
    GDFiterCellModel *orderInfoModel = [GDFiterCellModel new];
    orderInfoModel.cellKlass = HEMyOrderInfoCell.class;
    orderInfoModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
    
    
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[addAddrsModel, goodsModel, goodsOperationModel, footerModel,transFeeModel, askProxyPaynModel, proxyPaynModel, doctorModel, serverPersonModel,addOrderModel, orderInfoModel, headModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    self.formModel.od_itemList = @[].mutableCopy;
    NSInteger i = 0;
    for (GDFiterCellModel *model in classArr) {
         NSMutableArray *secs = [NSMutableArray array];
        
        // 隐藏未达到条件的cell
        if (model.cellDisplayType == GDCellDisplayNone) {
            continue;
        }
        else if (model.cellType == GDFiterCellTypeOrderDetailsGoodsFooter ||
                 model.cellType == GDFiterCellTypeOrderDetailsHead ||
                 model.cellType == GDFiterCellTypeOrderDetailsGoodsOperation) {
            continue;
        }
        else if (model.cellType == GDFiterCellTypeOrderDetailsGoods) {
            for (HEOrderItemModel *item in self.detials.orderItemList) {
                
                if(_type == HEOrderDetailsTypeByAfterList) { // 从售后列表进来，控制显示商品数量
                    BOOL hasAfterOrderItem = NO;
                    for (HEOrderItemModel *afterItem in _orderItems) {
                        if (afterItem.id == item.id) {
                            hasAfterOrderItem = YES;
                        }
                    }
                    
                    if (!hasAfterOrderItem) {
                        continue;;
                    }
                }
                
                [secs addObject:model];
                [self.formModel.od_itemList addObject:item]; // 填充good 和operation数据
                
                // 如果该账号是代付人，则不显示售后操作
                if (isProxyPerson) {
                    continue;
                }
                if (item.afterOperationStatus == HEOrderGoodsOperationTypeApplySales) {
                    [secs addObject:goodsOperationModel];
                    [self.formModel.od_itemList addObject:item];
                }else if (item.afterOperationStatus == HEOrderGoodsOperationTypeCancelApply) {
                    [secs addObject:goodsOperationModel];
                    [self.formModel.od_itemList addObject:item];
                }else if (item.refundStatus == HEOrderRefuseStatusWaitSellerReture) {
                    [secs addObject:goodsOperationModel];
                    [self.formModel.od_itemList addObject:item];
                }
            }
             
            [secs addObject:footerModel];
        }else if (model.cellType == GDFiterCellTypeOrderDetailsAddOrder) {
            GDFiterCellModel *hdModel = [GDFiterCellModel new];
            hdModel.cellKlass = HEMyOrderDetailsHeadCell.class;
            hdModel.cellType = GDFiterCellTypeOrderDetailsHead;
            hdModel.leftTitle = @"补单信息";
            [secs addObject:hdModel];

            for (HEOrderChildInfo *childInfo in self.detials.childInfo) {
                [secs addObject:model];
            }
        }
        else if (model.cellType == GDFiterCellTypeOrderDetailsOrderInfo) {
            [secs addObject:headModel];
            self.formModel.od_orderInfoItems = @[].mutableCopy;
            if (self.detials.orderSn) { // 订单号
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"订单编号：", @"value": _detials.orderSn};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.createTime) { // 创建时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"创建时间：", @"value": [NSDate timestampToDate:_detials.createTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.paymentTime &&
                (self.detials.status != HEOrderStatusClosed &&
                 self.detials.status != HEOrderStatusWaitPay)) { // 支付时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"支付时间：", @"value": [NSDate timestampToDate:_detials.paymentTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (![DYTools isBlankString:self.detials.payCode]) { // 支付编号
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"支付编号：", @"value": _detials.payCode};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.modifyTime) { // 修改时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"修改时间：", @"value": [NSDate timestampToDate:_detials.modifyTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.deliveryTime) { // 发货时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"发货时间：", @"value": [NSDate timestampToDate:_detials.deliveryTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.receiveTime) { // 收货时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"收货时间：", @"value": [NSDate timestampToDate:_detials.receiveTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.serviceTime) { // 预约时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"预约时间：", @"value": [NSDate timestampToDate:_detials.serviceTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.realWelfareTime) { // 实际上门服务时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"服务时间：", @"value": [NSDate timestampToDate:_detials.realWelfareTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.staffCompleteTime) { // 服务完成时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"完成时间：", @"value": [NSDate timestampToDate:_detials.staffCompleteTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
            if (self.detials.commentTime) { // 评价时间
                GDFiterCellModel *orderItemModel = [GDFiterCellModel new];
                orderItemModel.cellKlass = HEMyOrderInfoCell.class;
                orderItemModel.cellType = GDFiterCellTypeOrderDetailsOrderInfo;
                [secs addObject:orderItemModel];
                
                NSDictionary *dict = @{@"name": @"评价时间：", @"value": [NSDate timestampToDate:_detials.commentTime formaterMode:NSDateFormaterModeDefault]};
                [self.formModel.od_orderInfoItems addObject:dict];
            }
        }
        else {
            [secs addObject:model];
        }
        
        [_sections addObject:secs];
        i++;
    }
    [_tableView reloadData];
}

#pragma mark - private
- (BOOL)isProxyPerson {
    UserInfo *userInfo = [UserManager sharedUserManager].curUserInfo;
    // 判断是不是发起代付人
    BOOL isAskPay = NO;
    if (self.detials.KdoctorInfo.pay_agent_info != nil && [userInfo.id isEqualToString: self.detials.KdoctorInfo.old_info.id]) {
        isAskPay = YES;
    }
    return !isAskPay;
}

#pragma mark delegate datasource
- (NSInteger)numberOfSectionsInGroupShadowTableView:(GroupShadowTableView *)tableView {
    return _sections.count;
}

- (NSInteger)groupShadowTableView:(GroupShadowTableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)groupShadowTableView:(GroupShadowTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    
    return cell;
}

- (CGFloat)groupShadowTableView:(GroupShadowTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    return  [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    }];
}

#pragma mark - UITableViewDelegate
- (CGFloat)groupShadowTableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.firstObject;
    
    if (fiterModel.cellType == GDFiterCellTypeOrderGoods) {
        return CGFLOAT_MIN;
    }
    return 15;
}

- (UIView *)groupShadowTableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

- (void)groupShadowTableView:(GroupShadowTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    if (fiterModel.cellType == GDFiterCellTypeOrderDetailsAddOrder) {
        HEOrderChildInfo *addModel = self.formModel.od_details.childInfo[indexPath.row-1];
        HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
        vc.orderId = addModel.orderId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - HEOrderTabBarViewDelegate


#pragma mark - HEOrderGoodsOperationCellDelegate
- (void)orderGoodsOperationCell:(HEOrderGoodsOperationCell *)cell orderItem:(nonnull HEOrderItemModel *)orderItem  type:(HEOrderGoodsOperationType)type {
    
    if (type == HEOrderGoodsOperationTypeApplySales) {
        HEAfterSaleViewController *vc = [HEAfterSaleViewController new];
        vc.model = self.detials;
        orderItem.isChoose = YES;
        vc.orderItems = @[orderItem];
        [vc vcBackBlock:^{
            [self loadData];
            [self refreshBeforeVC];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (type == HEOrderGoodsOperationTypeCancelApply) {
        [WOAlert alertShowTitle:@"" message:@"您确定要取消申请售后吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self cancelAfterSale: orderItem.id];
            }
        }];
    }else if (type == HEOrderGoodsOperationTypeFill) {
        HEReturnLogisticsViewController *vc = [HEReturnLogisticsViewController new];
        vc.orderItems = @[orderItem];
        [vc vcBackBlock:^{
            [self loadData];
            [self refreshBeforeVC];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
    

}

- (void)cancelAfterSale:(NSInteger)orderItemId {
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KcancelRefund parameters:@{@"orderItemId": [NSNumber numberWithInteger:orderItemId]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"取消售后成功"];
            [self loadData];
            [self refreshBeforeVC];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - HEMyOrderTabbarViewDelegate
- (void)bottomOperationWithModel:(HEOrderModel *)model type:(HEOrderBottomBtnType)type {
    switch (type) {
        case HEOrderBottomBtnTypeToPay: {
            HEPayPopView *vc = [[HEPayPopView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kScreenHeight)];
            vc.detials = self.detials;
            vc.paymentsList = _paymentsList;
            vc.delegate = self;
            [[UIApplication sharedApplication].keyWindow addSubview:vc];
        }
            break;
        case HEOrderBottomBtnTypeCancelOrder:
        {
            [WOAlert alertShowTitle:@"" message:@"您确定要取消该订单吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self cancelOrder:model.id];
                }
            }];
        }
            break;
            
        case HEOrderBottomBtnTypeDelete:
        {
            [WOAlert alertShowTitle:@"" message:@"您确定要删除该订单吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self deleteOrder:model.id];
                }
            }];
        }
            break;
        case HEOrderBottomBtnTypeComment:
        {
            HEOrderCommentViewController *vc = [HEOrderCommentViewController new];
            vc.model = model;
            [vc vcBackBlock:^{
                [self refreshBeforeVC];
                [self loadData];
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case HEOrderBottomBtnTypeChecklogistics:
        {
            HELogisticsViewController *vc = [HELogisticsViewController new];
            vc.order = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case HEOrderBottomBtnTypeConfirmGoods:
        {
            [WOAlert alertShowTitle:@"" message:@"您确定收货吗？" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self confimDelivery:model.id];
                }
            }];
        }
            break;
        case HEOrderBottomBtnTypeApplysales:
        case HEOrderBottomBtnTypeBatchApplysales:
        {
            HEAfterSaleViewController *vc = [HEAfterSaleViewController new];
            vc.model = model;
            vc.orderItems = model.orderItemList;
            [vc vcBackBlock:^{
                [self loadData];
                [self refreshBeforeVC];
            }];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}
- (void)loadPaydata {
    
    _paymentsList = @[].mutableCopy;
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:Kpaymentlist parameters:@{@"appSource":@(KAppSource)} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        self.paymentsList = [HEPaymentModel mj_objectArrayWithKeyValuesArray:response.data];

    } failure:^(NSError * _Nonnull error) {
    }];
}

/** 删除订单*/
- (void)cancelOrder:(NSInteger)orderId {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KcloseOrder parameters:@{@"orderId" : [NSNumber numberWithInteger:orderId]} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"订单取消成功~"];
            [self loadData];
            [self refreshBeforeVC];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

/** 删除订单*/
- (void)deleteOrder:(NSInteger)orderId {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KdeleteOrder parameters:@{@"orderId" : [NSNumber numberWithInteger:orderId]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"订单删除成功~"];
            [self refreshBeforeVC];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/** 确定收货*/
- (void)confimDelivery:(NSInteger)orderId {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KconfimDelivery parameters:@{@"id" : [NSNumber numberWithInteger:orderId]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"确认收货成功~"];
            
            [self loadData];
            [self refreshBeforeVC];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)refreshBeforeVC {
    // 刷新订单列表
    if (self.backBlock) {
        self.backBlock();
    }
}


#pragma mark - 设置底部操作栏
- (void)setupTabbar {
     
    HEOrderModel *model = self.detials;
    
    BOOL isShow = NO;
    
    // 居家照料  护工订单
    if (model.channel == HEChannelTypeHomeCare && model.status != HEOrderStatusWaitPay) {
        switch (model.welfareStatus) {
            case HEOrderWelfareStatusEvaluated: // 待评价
            {
                isShow = YES;
            }
                break;
            case HEOrderWelfareStatusCanceled:
            case HEOrderWelfareStatusAutoRefurn:
            {
                isShow = YES;
            }
                break;
            default:
                isShow = NO;
                break;
        }
     
    }else {
        switch (model.status) {
            case HEOrderStatusWaitPay:
            {
                isShow = YES;
            }
                break;
            case HEOrderStatusWaitDeliver:
            {
   
            }
                break;
            case HEOrderStatusDelivered:
            {
                isShow = YES;
            }
                break;
            case HEOrderStatusWaitComment:
            {
                isShow = YES;
            }
                break;
            case HEOrderStatusFinish:
            case HEOrderStatusClosed:
            {
                isShow = YES;
            }
                break;
            default:
                isShow = NO;
                break;
        }
    }
    
    /**
     代付订单，是代付人，仅付款操作
     代付订单，不是代付人，可以全部操作操作，按正常逻辑来
     */
    if (self.detials.isAgent) {
        if ([self isProxyPerson] && self.detials.status != HEOrderStatusWaitPay) {
            isShow = NO;
        }
    }
    
    _tabbar.hidden = !isShow;
    if (isShow) {
        CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
        _tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight);
    }else {
        CGFloat tabbarHeight = 0 + KSafeTabbarHeight;
        _tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight);
    }
}

#pragma mark - HEMyOrderServicePersonCellDelegate
- (void)checkServerCommentsPage:(HEOrderServerInfo *)serverInfo {
    HEServerCommentListViewController *vc = [HEServerCommentListViewController new];
    vc.serverId = serverInfo.usid;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 待支付弹窗
- (void)popView:(id)payView payType:(NSString *)type {
    
    [HEPayManager sharedManager].order = self.detials;

    // 发起支付
    if ([type isEqualToString:KWxPayCode]) {
        [self createWxPayRequest:self.orderId];
    }else if ([type isEqualToString:KAliPayCode]) {
        [self createAliPayRequest:self.orderId];
    }else if ([type isEqualToString:KQRPayCode]) {
        [self showQRPay];
    }
}

#pragma mark 二维码支付
- (void)showQRPay {
    NSString *token = [[UserManager sharedUserManager] getToken];
    KWeakSelf
    [HEQRPayView showWithURL: [NSString stringWithFormat:@"https://www.honglutec.com/oldPay/codePage.html?appSource=%d&orderId=%ld&payPlatform=%@&token=%@&providerPay=%d", KAppSource, self.order.id, KPayPlatform, token, _order.storeId == 1 ? 0 : 1] cancelBlock:^{
        [weakSelf payFialure];
    }];
}

#pragma mark 请求支付宝支付串
- (void)createAliPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KAliAppPay : KAliAppProPay;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [[HEPayManager sharedManager] senAliPayRequest:response.data];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
#pragma mark 请求微信支付串
- (void)createWxPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KWxAppPay : KWxAppProPay;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters: dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        HEWxPayReqModel *wxModel = [HEWxPayReqModel mj_objectWithKeyValues:[DYTools getContainersObjectFromJsonString:response.data]];
            
        PayReq* req = [[PayReq alloc] init];
        req.partnerId = wxModel.partnerid;
        req.prepayId = wxModel.prepayid;
        req.nonceStr = wxModel.noncestr;
        req.timeStamp = wxModel.timestamp.unsignedIntValue;
        req.package = wxModel.package;
        req.sign = wxModel.sign;
        [WXApi sendReq:req completion:^(BOOL success) {
            if (!success) {
                [Dialog toastBottom:@"支付失败~"];
                [self payFialure];
            }
        }];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 支付回调
- (void)paySuccess {
    
    // 刷新订单详请
    [self loadData];
    
    // 刷新订单列表
    [self refreshBeforeVC];

        
    // 支付成功
     HEPayResultResViewController *vc = [HEPayResultResViewController new];
 
     [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
     }];
}

- (void)payFialure {

}

#pragma mark - HEMyOrderDoctorInfoCellDelegate 和医生私聊
- (void)orderDocInfoCell:(HEMyOrderDoctorInfoCell *)cell withExtra:(HEExtraDoctorInfoModel *)extra {
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;

    if (extra.order_type == HEChannelTypePrivateDoctors) {
        __weak typeof(self) weakself = self;
        [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KprivateDocinfo parameters:@{} success:^(id  _Nonnull responseObject) {
            HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
            HEDoctorInfoModel *docInfo = [HEDoctorInfoModel mj_objectWithKeyValues: response.data];
            
            if (response.success && response.data != nil && [docInfo.user_id isEqualToString:extra.doctor_info.user_id]) {
                HEIMKitInfo *doc = [HEIMKitInfo new];
                doc.infoId = extra.doctor_info.user_id;
                doc.showName = extra.doctor_info.realname;
                doc.avatarUrlString = extra.doctor_info.avatar;
                doc.avatarImage = IMAGE_NAMED(@"hmang");
                
                HEIMKitInfo *owner = [HEIMKitInfo new];
                owner.infoId = user.id;
                owner.showName = user.realname;
                owner.avatarUrlString = user.avatar;
                owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
                
                [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];
                
                HEIMChatViewController *imVC = [HEIMChatViewController new];
            //    imVC.isExprie = [@"1" isEqualToString:model.user_doc_flag]? NO:YES;
                imVC.docId = extra.doctor_info.user_id;
                [weakself.navigationController pushViewController:imVC animated:YES];
            }else {
                [Dialog toastBottom:@"私人医生已过期"];
            }
        } failure:^(NSError * _Nonnull error) {
        }];
    }else if(extra.order_type == HEChannelTypePTConsultation) {
        
        HEIMKitInfo *doc = [HEIMKitInfo new];
        doc.infoId = extra.doctor_info.user_id;
        doc.referenceId = extra.inst_id;
        doc.showName = extra.doctor_info.realname;
        doc.avatarUrlString = extra.doctor_info.avatar;
        doc.avatarImage = IMAGE_NAMED(@"hmang");
        
        HEIMKitInfo *owner = [HEIMKitInfo new];
        owner.infoId = user.id;
        owner.showName = user.realname;
        owner.avatarUrlString = user.avatar;
        owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
        
        [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];
        
        HEIMTWChatViewController *vc = [HEIMTWChatViewController new];
        vc.docId = extra.doctor_info.user_id;
        vc.inst_id = extra.inst_id;
        vc.docName = extra.doctor_info.realname;
        vc.backBlock = ^{
            [self.tableView.mj_header beginRefreshing];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else if (extra.order_type == HEChannelTypeDoctorTeam) {
        HEIMKitInfo *reciverInfo = [HEIMKitInfo new];
        reciverInfo.infoId = extra.team_info.groupId;
        reciverInfo.showName = extra.team_info.teamName;
        
        HEIMKitInfo *owner = [HEIMKitInfo new];
        owner.infoId = user.id;
        owner.showName = user.realname;
        owner.avatarUrlString = user.avatar;
        owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
        
        [[HEIMKit sharedKit] registeUserInfos: @[reciverInfo, owner]];

        HEIMTeamViewController *imVC = [HEIMTeamViewController new];
        imVC.teamId = reciverInfo.infoId;
        imVC.modelType = HEIMUserModelTypeTeamIM;
        [self.navigationController pushViewController:imVC animated:YES];
    }
}

#pragma mark - getter
- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (NSMutableArray *)goodsDataSource {
    if (!_goodsDataSource) {
        _goodsDataSource = [NSMutableArray array];
    }
    return _goodsDataSource;
}

- (UIImageView *)sealAllView {
    if (!_sealAllView) {
        _sealAllView = [UIImageView new];
        _sealAllView.image = IMAGE_NAMED(@"payed");
        _sealAllView.contentMode = UIViewContentModeScaleAspectFit;
        [_tableView addSubview:self.sealAllView];

        [_sealAllView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_tableView).offset(15);
            make.width.height.mas_equalTo(80);
            make.left.equalTo(_tableView).offset(KScreenWidth-80-30);
        }];
    }
    return _sealAllView;
}
 
@end
